package org.oreilly.javaGoodParts.examples.impl;

import java.util.Comparator;

import org.oreilly.javaGoodParts.examples.statistics.Batter;
import org.oreilly.javaGoodParts.examples.statistics.NotEnoughAtBatsException;
import org.oreilly.javaGoodParts.examples.statistics.Player;

import com.google.common.collect.ComparisonChain;

/**
 * A comparitor that will rank players depending on
 * their batting average. If both players have a
 * batting average, the one with the higher average
 * is compared as greater than the other. Players with
 * insufficient at bats or who don't bat at all are
 * dealt with as if their batting average is 0. If two
 * players have the same batting average, they will
 * be compared based on their player ids, which are
 * guaranteed to be unique.
 *
 * This comparison will give a well-ordering to any
 * collection of players, based on their batting average.
 * Ties are broken by using the Id field of the player, which
 * is also used to determine equality
 */
public class BattingComparator implements Comparator<Player>{

    @Override
    public int compare(Player o1, Player o2) {
        return ComparisonChain.start()
    		.compare(getBattingAverage(o1), getBattingAverage(o2))
    		.compare(o1.getId(), o2.getId()).result();
    }

    private static float getBattingAverage(Player player) {
    	float avg = 0.0f;
    	if (player.hasRole(Player.Roles.Batter)) {
            try {
                avg = player.adapt(Batter.class).getAverage();
            } catch (NotEnoughAtBatsException e){
            }
    	}
    	return avg;
    }
}
